<script>
import kefuIcon from "../assets/kefu.png"
import contractKeFu from "../../../components/contractKeFu/index.vue"
import agreement from "./agreement.vue"
import {
  checkBindPhone,
  getShowImage,
  handleMoney,
  handleMonkeyRow,
  handleUrlParams,
  showModal,
  showModalPromise,
  showToast,
} from "@/utils"
import request from "@/utils/request"
import store from "@/store"
import { userActionType } from "@/store/modules/user"
import pay from "@/utils/pay"
import persistence from "@/store/persistence"
import giftIcon from "../assets/gift.png"
import urlUtils from "@/utils/urlUtils"
import { getEnv } from "@/utils/settings"
import numberUtils from "@/utils/numberUtils"
import bindPhoneNumberPopup from "@/components/bindPhoneNumberPopup/index.vue"
import { vocabularyLearningActionType } from "@/store/modules/vocabularyLearning"

export default {
  name: "footer",
  computed: {
    numberUtils() {
      return numberUtils
    },
    urlUtils() {
      return urlUtils
    },
  },
  components: { contractKeFu, agreement, bindPhoneNumberPopup },
  data() {
    return {
      hasAgreement: false, // 是否同意协议
      kefuIcon,
      giftIcon,
      messageTemplateList: {
        teamwork: [], // 商品拼团通知
        assignment: [], // 作业布置通知
      },
      takingOrder: false, //是否正在下单（避免重复触发下单按钮）
    }
  },
  props: {
    details: {
      type: Object,
      default: () => {},
    },
    teamBuyingDetails: Array, //拼团详情
    myTeamBuyingDetails: Object, //我的拼团详情
    shareUserGroupIdentification: String, //分享人的拼团标识
    shareTeamBuyingPrice: Number, //分享人的拼团价格
  },
  created() {
    //获取微信订阅消息模板列表
    request({
      url: "wxMessageTemplate/listTemplate",
      data: {
        // 商品拼团通知、作业布置通知
        templateSceneList: ["Teamwork", "Assignment"],
      },
      errorHandle: true,
      showLoading: true,
    }).then((data) => {
      if (data && data.length > 0) {
        data.forEach((item) => {
          // 根据模板场景分类
          if (item.templateSceneCode === "Teamwork") {
            this.messageTemplateList.teamwork.push(item.templateId)
          } else if (item.templateSceneCode === "Assignment") {
            this.messageTemplateList.assignment.push(item.templateId)
            this.messageTemplateList.teamwork.push(item.templateId)
          }
        })
      }
      console.log(this.messageTemplateList, "获取到的订阅消息模板列表")
    })
  },
  methods: {
    handleMoney,
    handleMonkeyRow,
    getShowImage,
    //用户协议点击事件
    handleAgreementClick() {
      //还未阅读过
      if (!this.hasAgreement) {
        this.$refs.agreement.open()
      } else {
        this.hasAgreement = false
      }
    },
    //下单前检查用户是否有同意协议
    checkAgreement() {
      return new Promise((resolve, reject) => {
        //价格为0不需要同意协议
        if (this.details.price === 0) {
          resolve()
          return
        }
        if (!this.hasAgreement) {
          this.$refs.agreement
            .open()
            .then(() => {
              resolve()
            })
            .catch(() => {
              reject()
            })
        } else {
          resolve()
        }
      })
    },
    // 下订单购买课程
    async purchaseCourse() {
      if (this.takingOrder) return
      try {
        //检查是否有绑定手机号码
        await this.checkBindPhone()
        this.takingOrder = true
        //价格为0时不需要同意协议
        //未同意协议不允许下单
        await this.checkAgreement()
        //弹出订阅消息申请弹窗
        await this.openSubscribeMessagePopup("assignment")
        uni.showLoading({
          title: "处理中...",
          mask: true,
        })
        //发送请求创建订单
        await this.takeOrder()
        //刷新详情
        this.$emit("getDetails")
        //配置了加v二维码弹出二维码让用户加v
        if (this.details.contactQrcode) {
          await this.openAfterBuyingKeFuPopup()
          //下单购买类型需要跳转到h5
        } else if (this.details.businessType === "CreateOrder") {
          uni.showLoading({
            title: "处理中...",
            mask: true,
          })
          setTimeout(() => {
            uni.hideLoading()
            this.goToH5()
          }, 2000)
        }
      } catch (e) {
        console.log(e, "e")
        await showModal({
          title: "提示",
          content: e,
          showCancel: false,
        })
      } finally {
        this.takingOrder = false
        uni.hideLoading()
      }
    },
    // 购买带背词库
    async purchaseRackedThesaurus() {
      try {
        await this.takeOrder()
        this.$emit("getDetails")
				await showModalPromise({
					content: "购买成功",
					confirmText: "前往学习",
					showCancel: false,
				})
				// 切换到对应的考试
				try {
					uni.showLoading({
						title: "加载中...",
						mask: true,
					})
					await request({
						url: "exam/saveUserSelectExam",
						data: {
							examId: this.details.examId,
						},
					})
					await store.dispatch(userActionType.action.refreshUserInfo)
				} catch (e) {
					console.log(e, "e")
				} finally {
					uni.hideLoading()
				}
        // 跳转到计划详情页面
        uni.reLaunch({
          url: handleUrlParams(
						"/vocabulary/pages/currentPlanInfo/index"
					),
        })
			} catch (e) {
        showToast.default(e)
        console.log(e, "error")
      }
    },
    //发送请求创建订单
    async takeOrder() {
      let data = await request({
        url: "courseRegisteredUser/createOrder",
        data: {
          classId: this.details.id,
          username: (await store.dispatch(userActionType.action.userInfo)).nickName,
          exclusiveId: this.parent.exclusiveId, //下单专属码id
          userCouponId: this.parent.userCouponId, //优惠券id
          shareUserId: persistence.shareType.get() === "inviteCashBack" ? persistence.inviteUserId.get() : "", //邀请活动邀请人id
        },
        errorHandle: true,
      })
      //发起支付
      await pay.handlePay(data)
    },
    async goToH5() {
      try {
        uni.showLoading({
          title: "加载中...",
          mask: true,
        })
        //弹出订阅消息申请弹窗
        await this.openSubscribeMessagePopup("assignment")
        //获取h5地址
        const data = await request({
          url: "courseRegisteredUser/getH5Url",
          showLoading: true,
          data: {
            classId: this.details.id,
          },
        })
        uni.navigateTo({
          url: handleUrlParams("/pages/web-view/web-view", {
            path: encodeURIComponent(data),
          }),
        })
      } catch (err) {
        await showModal({
          title: "提示",
          content: err,
        })
        console.log(err, "err")
      } finally {
        uni.hideLoading()
      }
    },
    // 下单完成后弹出二维码
    async openAfterBuyingKeFuPopup() {
      //弹出订阅消息申请弹窗
      this.$refs["kefu-popup"].open()
    },
    //检查绑定手机号码
    async checkBindPhone() {
      return await this.$refs.bindPhoneNumberPopup.open()
    },
    // 关闭二维码弹窗
    async handleAfterBuyingKeFuPopupClose() {
      this.$refs["kefu-popup"].close()
      //下单购买类型需要跳转到h5
      if (this.details.businessType === "CreateOrder") {
        await this.goToH5()
      }
    },
    //获取订阅消息设置
    getSubscriptionSettings() {
      return new Promise((resolve, reject) => {
        console.log("getSubscriptionSettings")
        uni.getSetting({
          withSubscriptions: true,
          success: (res) => {
            console.log(res, "settings")
            resolve(res)
          },
          fail(err) {
            console.log(err, "获取订阅消息设置失败")
            reject(err)
          },
        })
      })
    },
    //发起消息订阅
    requestSubscriptionMessage(messageTemplateList) {
      return new Promise((resolve, reject) => {
        console.log("requestSubscriptionMessage")
        if (messageTemplateList.length === 0) {
          resolve()
          return
        }
        console.log(messageTemplateList, "拉取订阅消息")
        uni.requestSubscribeMessage({
          tmplIds: messageTemplateList,
          success(res) {
            console.log(res, "订阅消息模板成功")
            resolve(res)
          },
          fail(err) {
            console.log(err, "订阅消息失败")
            resolve()
          },
        })
      })
    },
    //弹出订阅消息订阅弹窗
    //type: "teamwork" 商品拼团通知 "assignment" 作业布置通知
    openSubscribeMessagePopup(type = "assignment") {
      return new Promise((resolve, reject) => {
        const messageTemplateList = this.messageTemplateList[type]
        console.log("openSubscribeMessagePopup")
        this.getSubscriptionSettings()
          .then(() => {
            this.requestSubscriptionMessage(messageTemplateList).finally(() => {
              resolve()
            })
          })
          .catch((err) => {
            resolve()
          })
      })
    },
    //发起拼团或者加入别人的拼团
    //type "teamwork" 发起拼团 "joinGroup" 加入拼团
    async teamBuyingTakeOrder(type) {
      if (this.takingOrder) return
      try {
        this.takingOrder = true
        //绑定手机号码
        await this.checkBindPhone()
        this.takingOrder = false
        //同意协议
        await this.checkAgreement()
        //消息订阅
        await this.openSubscribeMessagePopup("teamwork")
        if (type === "teamwork") {
          await this.parent.$refs.teamBuying.chooseTeamMemberCount()
        } else if (type === "joinGroup") {
          await this.parent.$refs.teamBuying.joinGroup()
        }
        //用户拒绝了消息订阅提示开启
        this.getSubscriptionSettings().then((res) => {
          function showTips() {
            showModal({
              title: "提示",
              content: "您已关闭订阅消息，将无法收到拼团通知，是否前往开启",
              confirmText: "前往开启",
            }).then((res) => {
              if (res) {
                uni.openSetting()
              }
            })
          }
          const subscriptionsSetting = res.subscriptionsSetting
          if (!subscriptionsSetting) return
          if (!subscriptionsSetting.mainSwitch) {
            showTips()
            return
          }
          if (!subscriptionsSetting.itemSettings || Object.keys(subscriptionsSetting.itemSettings).length === 0) return
          let allSubscribe = true
          for (let itemSettingsKey in subscriptionsSetting.itemSettings) {
            //筛选出所有和拼团和作业相关的订阅消息
            if (
              !this.messageTemplateList.teamwork.includes(itemSettingsKey) &&
              !this.messageTemplateList.assignment.includes(itemSettingsKey)
            )
              continue
            if (subscriptionsSetting.itemSettings[itemSettingsKey] === "reject") {
              allSubscribe = false
              break
            }
          }
          if (allSubscribe) return
          showTips()
        })
      } catch (e) {
        console.log(e, "error")
      } finally {
        this.takingOrder = false
      }
    },
  },
  inject: ["parent"],
  emits: ["getDetails"],
}
</script>

<template>
  <view>
    <!--		占位-->
    <view style="height: 300rpx"></view>
    <view class="footer">
      <!--			商品已下架、带背词汇类型、价格为0、已经购买了不展示-->
      <!--			用户服务协议-->
      <view
        class="row agreement"
        v-if="details.businessType !== 'Racked' && details.salesStatus !== 2 && details.price > 0 && details.isRegistered === 0"
        @click.stop="handleAgreementClick"
      >
        <checkbox :checked="hasAgreement"></checkbox>
        <text class="text">我已阅读并同意</text>
        <text class="theme-color">《用户服务协议》</text>
      </view>
      <view class="row btn-list">
        <!--				联系客服-->
        <view class="btn-item" @click="() => $refs.contractKeFu.open()">
          <image class="icon" :src="kefuIcon"></image>
          <text>联系客服</text>
        </view>
        <!--				邀请有礼活动-->
        <!--				商品已下架时不展示-->
        <view
          class="btn-item"
          v-if="details.sharingActivitiesStatus === 'On' && details.salesStatus !== 2"
          @click="() => $uni.navigateTo({ url: urlUtils.handleUrlParams('/pages/course/sharePage', { id: details.id }) })"
        >
          <image class="icon" :src="giftIcon"></image>
          <text style="color: #f06220">分享有礼</text>
        </view>
        <!--				总价（优惠后的价格）-->
        <!--				商品未下架、之前没有购买过、价格不为0时才展示-->
        <!--				拼团模式价格嵌进按钮里面的所以不展示-->
        <view class="sum-price">
          <template v-if="details.salesStatus !== 2 && details.isRegistered === 0 && details.price !== 0 && teamBuyingDetails.length === 0">
            <view>合计:</view>
            <view style="color: #de0000">￥</view>
            <view class="number">{{ handleMonkeyRow(parent.sum) }}</view>
          </template>
        </view>
        <!--				带背词库类型-->
        <template v-if="details.businessType === 'Racked'">
          <!--					价格为0 -->
          <view class="take-order primary" v-if="details.price === 0" @click="purchaseRackedThesaurus">0元下单</view>
          <view class="take-order" @click="purchaseRackedThesaurus" v-else-if="details.isRegistered === 0">立即购买</view>
          <view
            class="take-order primary"
            v-else
            @click="() => $uni.reLaunch({ url: '/vocabulary/pages/currentPlanInfo/index' })"
            >前往学习</view
          >
        </template>
        <!--下单购买、课程预约、训练营类型-->
        <template v-else-if="['CreateOrder', 'CourseReservation', 'TrainingCamp'].includes(details.businessType)">
          <!--					已经购买过了-->
          <template v-if="details.isRegistered === 1">
            <!--					下单购买和课程预约类型-->
            <view class="take-order primary" @click="goToH5" v-if="['CreateOrder', 'CourseReservation'].includes(details.businessType)"
              >前往学习</view
            >
            <!--					训练营类型-->
            <view class="take-order primary" @click="openAfterBuyingKeFuPopup" v-else-if="details.businessType === 'TrainingCamp'"
              >已加入</view
            >
          </template>
          <!--					已经下架-->
          <view class="take-order light" v-else-if="details.salesStatus === 2">已下架</view>
          <!--					还未购买过-->
          <template v-else>
            <!--					免费商品-->
            <template v-if="details.price === 0">
              <!--						特训营类型-->
              <view class="take-order" @click="purchaseCourse" v-if="details.businessType === 'TrainingCamp'">加入特训营</view>

              <view v-else class="take-order primary" @click="purchaseCourse">前往学习</view>
            </template>
            <!--					付费商品-->
            <template v-else>
              <!--					配置了拼团-->
              <template v-if="teamBuyingDetails.length > 0">
                <!--				被分享人分享进来不显示			-->
                <view class="take-order light slim" @click="purchaseCourse" v-if="!shareUserGroupIdentification">
                  <view>{{ `￥${handleMoney(parent.sum)}` }}</view>
                  <view>单独购买</view>
                </view>
                <!--							用户之前加入了拼团-->
                <view
                  class="take-order slim"
                  @click="() => parent.$refs.teamBuying.checkTeamBuyingProgress()"
                  v-if="myTeamBuyingDetails && myTeamBuyingDetails.commodityGroupBuy && myTeamBuyingDetails.commodityGroupBuy.groupBuyId"
                >
                  <view>拼团详情</view>
                </view>
                <!--							还未加入拼团-->
                <template v-else>
                  <!--									被邀请进来加团-->
                  <view
                    class="take-order slim"
                    @click="() => parent.$refs.teamBuying.viewTeamInfo().then(() => teamBuyingTakeOrder('joinGroup'))"
                    v-if="shareUserGroupIdentification"
                  >
                    <view>{{ `￥${numberUtils.fenToYuan(shareTeamBuyingPrice)}` }}</view>
                    <view>加入拼团</view>
                  </view>
                  <!--									自己发起拼团-->
                  <view class="take-order slim" @click="() => teamBuyingTakeOrder('teamwork')" v-else>
                    <view>{{ `￥${numberUtils.fenToYuan(teamBuyingDetails[teamBuyingDetails.length - 1].price)}起` }}</view>
                    <view>多人拼团</view>
                  </view>
                </template>
              </template>
              <!--					没有配置拼团-->
              <view class="take-order" @click="purchaseCourse" v-else>
                <!--						下单购买类型-->
                <text v-if="details.businessType === 'CreateOrder'">立即购买</text>
                <!--						课程预约类型-->
                <text v-else-if="details.businessType === 'CourseReservation'">立即预约</text>
                <!--						训练营类型-->
                <text v-else-if="details.businessType === 'TrainingCamp'">加入特训营</text>
              </view>
            </template>
          </template>
        </template>

        <!--				弹框扫码类型，无需调用下单接口-->
        <template v-else-if="details.businessType === 'PopFrame'">
          <view class="take-order slim primary" @click="openAfterBuyingKeFuPopup">联系老师，了解详情</view>
        </template>
      </view>
    </view>
    <!--		联系客服-->
    <contract-ke-fu ref="contractKeFu"></contract-ke-fu>
    <!--		用户协议-->
    <agreement ref="agreement" :hasAgreement.sync="hasAgreement"></agreement>
    <!--		下单完成后展示二维码提示用户加v-->
    <uni-popup ref="kefu-popup" type="dialog">
      <uni-popup-dialog
        mode="content"
        title="温馨提示"
        :before-close="true"
        :showClose="false"
        confirmText="我已扫描二维码"
        @confirm="handleAfterBuyingKeFuPopupClose"
      >
        <image :src="getShowImage(details.contactQrcode)" mode="widthFix" class="kefu-qr-code" :show-menu-by-longpress="true"></image>
      </uni-popup-dialog>
    </uni-popup>
    <!--		绑定手机号码组件-->
    <bindPhoneNumberPopup reason="报名课程，为了后续课程开课服务通知，需要提供手机号码" ref="bindPhoneNumberPopup"></bindPhoneNumberPopup>
  </view>
</template>

<style scoped lang="scss">
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: {
    top: 20rpx;
    left: 20rpx;
    right: 20rpx;
    bottom: calc(20rpx + env(safe-area-inset-bottom));
  }
  background: white;
  box-shadow: 0 -1rpx 10rpx 0 rgba(0, 0, 0, 0.1);
  .sum-price {
    width: 0;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: flex-end;
    font-size: 30rpx;
    line-height: 1;
    .number {
      color: #de0000;
      font-size: 36rpx;
      font-weight: 600;
    }
  }
  .row {
    display: flex;
    align-items: center;
    &:not(:last-child) {
      margin-bottom: 30rpx;
    }
    &.agreement {
      font-size: 28rpx;
      width: max-content;
      .text {
        margin-left: 10rpx;
      }
      .theme-color {
        color: var(--text-color-theme);
      }
    }
    &.btn-list {
    }
    .btn-item {
      display: flex;
      align-items: center;
      flex-direction: column;
      font-size: 26rpx;
      &:not(:first-child) {
        margin-left: 30rpx;
      }
      .icon {
        width: 40rpx;
        height: 40rpx;
        margin-bottom: 6rpx;
      }
    }
    .take-order {
      background: #ee6326;
      color: white;
      font-size: 32rpx;
      height: 100rpx;
      padding: 0 60rpx;
      border-radius: 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      &:not(:first-child) {
        margin-left: 20rpx;
      }
      &.primary {
        background: #2979ff;
      }
      &.light {
        background: #a4adb3;
        color: #ffffff;
      }
      &.slim {
        padding: 0 40rpx;
        font-size: 30rpx;
      }
    }
  }
}
.kefu-qr-code {
  width: 100%;
}
</style>
